<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button v-if="checkPermission('addEmployee')" size="small" type="primary" @click="addEmployee">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card
        v-loading="loading"
        element-loading-text="拼命加载中"
      >
        <el-table border :data="employeesList">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="头像" sortable="" prop="staffPhoto" width="200">
            <template #default="obj">
              <img ref="imgDef" v-fixImg="require('@/assets/common/head.jpg')" class="imgDef" :src="obj.row.staffPhoto" alt="" style="width:180px;height:120px;" @click="showQRcode(obj.row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployee" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" align="center" prop="timeOfEntry">
            <!-- 作用域插槽 -->
            <template #default="obj">
              {{ obj.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template #default="obj">
              <el-switch
                v-model="obj.row.enableState"
                :active-value="1"
                :inactive-value="2"
                active-color="green"
                inactive-color="red"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="obj">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${obj.row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showAssign(obj.row.id)">角色</el-button>
              <el-button v-if="checkPermission('delEmployee')" type="text" size="small" @click="delEmployee(obj.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :page-size="page.size"
            :current-page="page.page"
            :total="page.total"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
      <addEmployee :is-show-dialog="isShowDialog" />
      <el-dialog title="头像二维码" :visible="isShowQRcode" @close="isShowQRcode = false">
        <el-row>
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <assign ref="assign" :is-show-assign.sync="isShowAssign" />
    </div>
  </div>
</template>

<script>
import { delEmployee, getEmployeesList } from '@/api/employee'
import employeeConstant from '@/api/constant/employees'
import { export_json_to_excel } from '@/components/vendor/Export2Excel'
import addEmployee from '@/views/employees/component/addEmployee.vue'
import QRcode from 'qrcode'
import assign from './component/assign.vue'

export default {
  components: {
    addEmployee,
    assign
  },
  data() {
    return {
      isShowAssign: false,
      isShowQRcode: false,
      loading: false,
      isShowDialog: false,
      employeesList: [],
      page: {
        page: 1, // 当前页码
        size: 5,
        total: 0 // 总数
      }
    }
  },
  async created() {
    this.loading = true
    await this.getEmployeeList()
  },
  methods: {
    // 显示角色弹窗
    async showAssign(id) {
      await this.$refs.assign.getEmployeeInfo(id)
      this.isShowAssign = true
    },
    // 关闭角色弹窗
    closeAssign() {
      this.isShowAssign = false
    },
    // 显示头像二维码
    showQRcode(url) {
      if (url) {
        this.isShowQRcode = true
        this.$nextTick(() => {
          QRcode.toCanvas(this.$refs.myCanvas, url)
        })
      }
    },
    changePage(newPage) {
      this.page.page = newPage
      this.getEmployeeList()
    },
    async getEmployeeList() {
      this.loading = true
      const { rows, total } = await getEmployeesList(this.page)
      this.employeesList = rows.map(user => {
        const state = Math.round(Math.random())
        return {
          ...user,
          enableState: user.enableState || state
        }
      })
      this.page.total = total
      this.loading = false
      console.log(55, rows, total)
    },
    formatEmployee(row, col, cellVal) {
      const obj = employeeConstant.hireType.find(item => Number(item.id) === Number(cellVal))
      return obj ? obj.value : '未知'
    },
    // 导出员工列表
    async exportExcel() {
      const { rows } = await getEmployeesList({
        page: 1, // 当前页码
        size: this.page.total })
      console.log(rows)
      const header = ['姓名', '工号', '手机号码', '入职时间', '转正时间', '聘用形式']
      const data = rows.map(user => {
        return this.objToArr(user)
      })
      console.log(117, data)
      export_json_to_excel({
        header,
        data
      })
    },
    objToArr(data) {
      const dict = { '姓名': 'username', '工号': 'workNumber', '手机号码': 'mobile', '入职时间': 'timeOfEntry', '转正时间': 'correctionTime', '聘用形式': 'formOfEmployment' }
      const newData = []
      for (const key in dict) {
        const enkey = dict[key]
        const val = data[enkey]
        // 时间和聘用形式转换
        if (enkey === 'timeOfEntry' || enkey === 'correctionTime' || enkey === 'formOfEmployment') {
          if (enkey === 'formOfEmployment') {
            const obj = employeeConstant.hireType.find(item => Number(item.id) === Number(val))
            newData.push(obj ? obj.value : '未知')
            console.log('聘用形式', obj)
          } else {
            this.formatExcelTime(val)
            newData.push(new Date(val))
            console.log('时间格式', val)
          }
        } else {
          newData.push(val)
        }
      }
      console.log(130, newData)
      return newData
    },
    formatExcelTime(num, format = '-') {
      num = Number(num)	// 强制类型转化，以防传来的值是字符串
      let millisecond = 0	// 转化后的毫秒数
      if (num > 60) {
        millisecond = (num - 25569) * 60 * 60 * 24 * 1000
      } else {
        millisecond = (num - 25568) * 60 * 60 * 24 * 1000
      }
      const date = new Date(millisecond)	// 根据转化后的毫秒数获取对应的时间
      const yy = date.getFullYear()
      const mm = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      const dd = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      return yy + format + mm + format + dd	// 返回格式化后的日期
    },
    // 删除员工
    async delEmployee(id) {
      await this.$confirm('是否确认删除该员工?')
      await delEmployee(id)
      this.$message.success('删除员工成功')
      if (this.employeesList.length === 1 && this.page.page > 1) {
        this.page.page--
      }
      this.getEmployeeList()
    },
    // 新增员工
    addEmployee() {
      this.isShowDialog = true
    }
  }

}
</script>

<style lang="scss" >
img{
  width: 100%;
  object-fit: cover;
}
//本来想伪元素给图片加占位符的,但是没做出来......
// ::v-deep .el-table__row{
//   ::v-deep .imgDef{
//   position: relative;
//   &::after{
//     content: "";
//     height:100px !important;
//     width: 100px; position: absolute; left: 0; top: 0;background-color: #000; background: url('../../assets/common/2053491.jpg') no-repeat center;
//   }
// }
// }
</style>
